package orxatas.travelme.sync;

import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import orxatas.travelme.activity.AsyncActivity;
import orxatas.travelme.databases.TravelmeDatabase;
import orxatas.travelme.databases.exceptions.UserNotInLocal;
import orxatas.travelme.entity.Group;
import orxatas.travelme.entity.User;
import orxatas.travelme.manager.AccountManager;
import orxatas.travelme.manager.UserManager;
import orxatas.travelme.sync.SyncOptions.ParseAnswer;

public class SyncUser extends SyncOptions {
	private UserManager userManager;
	private AsyncActivity asyncActivity;
	
	/**
	 * Base de datos.
	 * */
	private SQLiteDatabase trvlmdb;
	private TravelmeDatabase databaseHelper;
	
	public SyncUser(UserManager userManager, AsyncActivity asyncActivity){
		this.userManager = userManager;
		this.asyncActivity = asyncActivity;
		
		databaseHelper = new TravelmeDatabase(asyncActivity.getActivity(), new AccountManager(asyncActivity).getUserLogged().getId());
	}
	
	public User getUser(int idUser) throws UserNotInLocal{
		User user=getUserFromDB(idUser);
		if(user == null){
			new getUserCall(idUser).execute();
			userManager.syncInProgress();
			throw new UserNotInLocal(idUser);
		}
		
		return user;
	}
	
	private User getUserFromDB(int idUser){
		trvlmdb = databaseHelper.getReadableDatabase();
		Cursor c = trvlmdb.rawQuery("SELECT * FROM "+TravelmeDatabase.USER_TNAME+" WHERE "+TravelmeDatabase.USER_CID+" = "+idUser, null);
		
		if(!c.moveToFirst()){
			c.close();
			trvlmdb.close();
			return null;
		}
		
		int idc_id = c.getColumnIndex(TravelmeDatabase.USER_CID);
		int idc_name = c.getColumnIndex(TravelmeDatabase.USER_CNAME);
		int idc_email = c.getColumnIndex(TravelmeDatabase.USER_CEMAIL);
		int idc_lastupdate = c.getColumnIndex(TravelmeDatabase.USER_CLASTUPDATE);
		
		int id = c.getInt(idc_id);
		String name = c.getString(idc_name);
		String email = c.getString(idc_email);
		int lastUpdate = c.getInt(idc_lastupdate);
		
		User user = new User(id, email);
		user.setUserName(name);
		user.setLastUpdate(lastUpdate);
		
		c.close();
		trvlmdb.close();
		
		return user;
	}
	
	private class AnswerGetUser extends Answer<User>{}
	private class getUserCall extends AsyncInternetConnection {

		private int idUser;
		public getUserCall(int idUser) {
			super(TRVLMWS);
			
			this.idUser = idUser;
			
			List<NameValuePair> pairs = basicGETParams(new AccountManager(asyncActivity), METHOD_UM, ACTION_UM_GET);
			pairs.add(new BasicNameValuePair("uid", ""+idUser));
			addGETParams(pairs);
		}

		@Override
		protected void onPostExecute(String response) {
			try {
				Answer<User> answer = new ParseAnswer<AnswerGetUser>().parse(response, true, AnswerGetUser.class);
				if(answer.getState() == 0) return;
				
				User newu = answer.getObj();
				User oldu = getUserFromDB(idUser);
				
				trvlmdb = databaseHelper.getWritableDatabase();
				if(oldu != null && newu.getLastUpdate() > oldu.getLastUpdate()){
					ContentValues v = new ContentValues();
					v.put(TravelmeDatabase.USER_CNAME, newu.getUserName());
					v.put(TravelmeDatabase.USER_CEMAIL, newu.getEmail());
					v.put(TravelmeDatabase.USER_CLASTUPDATE, newu.getLastUpdate());
					
					trvlmdb.update(TravelmeDatabase.USER_TNAME, v, TravelmeDatabase.USER_CID+" = "+newu.getId() ,  null);
				} if(oldu != null) {
					ContentValues v = new ContentValues();
					v.put(TravelmeDatabase.USER_CID, newu.getId());
					v.put(TravelmeDatabase.USER_CEMAIL, newu.getEmail());
					v.put(TravelmeDatabase.USER_CNAME, newu.getUserName());
					v.put(TravelmeDatabase.USER_CLASTUPDATE, newu.getLastUpdate());
					
					trvlmdb.insert(TravelmeDatabase.USER_TNAME, null, v);
				}
				trvlmdb.close();
				
			} catch (WithoutObject e) {
				trvlmdb = databaseHelper.getWritableDatabase();
				trvlmdb.delete(TravelmeDatabase.USER_TNAME, TravelmeDatabase.USER_CID+" = "+idUser ,  null);
				trvlmdb.close();
			}
			
			userManager.syncInProgressEnd();
			userManager.asyncNotice(AsyncNoticeCode.USERS_CHANGED);
		}
	}
}
